import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import {
  Button,
  Row,
  Col,
  Form,
  Select,
  Input,
  Table,
  Tag,
  Popconfirm,
  message,
} from "antd";
import {} from "@ant-design/icons";

const { Option } = Select;

function Shop() {
  let navigate = useNavigate();
  const [dataSource, setDataSource] = useState([]); //数据源
  const [searchForm] = Form.useForm();
  const [count, setCount] = useState(1); //控制启用/停用门店
  const [pageArray, setPageArray] = useState([]); //分页页码数组
  const [totalPageCount, setTotalPageCount] = useState(); //总页数
  const [index, setIndex] = useState(1); //当前页码
  const [pageSize, setPageSize] = useState(10); //每页记录数据条数

  //开关门店
  const switchShop = (enabled, businessNo, version) => {
    if (enabled) {
      const instance = axios.create({
        headers: { tenantId: 500, userId: 11000 },
      });
      instance
        .post(`/shop/${businessNo}/close`, { version: version })
        .then((res) => {
          if (res.data.status.code === 0) {
            message.success("操作成功");
            setCount(count + 1);
          } else if (res.data.status.code === 630003) {
            message.error("当前数据与最新数据不一致，页面将刷新，请重新操作");
            window.location.reload();
          } else {
            message.error(res.data.status.msg);
          }
        });
    } else {
      const instance = axios.create({
        headers: { tenantId: 500, userId: 11000 },
      });
      instance
        .post(`/shop/${businessNo}/open`, { version: version })
        .then((res) => {
          if (res.data.status.code === 0) {
            message.success("操作成功");
            setCount(count + 1);
          } else if (res.data.status.code === 63003) {
            setCount(count + 1);
            message.error("当前数据与最新数据不一致，页面将刷新，请重新操作");
          } else {
            message.error(res.data.status.msg);
          }
        });
    }
  };

  //分页查询门店
  const searchForPage = (pageIndex, pageSize, condition) => {
    console.log(condition);
    const instance = axios.create({
      headers: { tenantId: 500, userId: 11000 },
    });
    instance
      .post("/shop/search", {
        condition: condition,
        pageIndex: pageIndex,
        pageSize: pageSize,
        sortFields: [
          { asc: false, field: "enabled" },
          { asc: false, field: "last_modified_at" },
          { asc: false, field: "created_at" },
        ],
      })
      .then((res) => {
        console.log(res);
        setDataSource([].concat(res.data.data.records));
        setTotalPageCount(res.data.data.totalPageCount);
        if (res.data.data.totalPageCount <= 5) {
          const arr = [];
          for (var i = 1; i <= res.data.data.totalPageCount; i++) {
            arr.push(i);
          }
          setPageArray([].concat(arr));
        } else {
          if (res.data.data.pageIndex <= 3) {
            setPageArray([].concat([1, 2, 3, 4, 5]));
          } else if (
            res.data.data.pageIndex > 3 &&
            res.data.data.pageIndex < res.data.data.totalPageCount - 2
          ) {
            setPageArray(
              [].concat([
                res.data.data.pageIndex - 2,
                res.data.data.pageIndex - 1,
                res.data.data.pageIndex,
                res.data.data.pageIndex + 1,
                res.data.data.pageIndex + 2,
              ])
            );
          } else {
            setPageArray(
              [].concat([
                res.data.data.totalPageCount - 4,
                res.data.data.totalPageCount - 3,
                res.data.data.totalPageCount - 2,
                res.data.data.totalPageCount - 1,
                res.data.data.totalPageCount,
              ])
            );
          }
        }
      });
  };

  useEffect(() => {
    searchForPage(index, pageSize, searchForm.getFieldsValue(true));
  }, [index, pageSize, count]);

  const shopColumns = [
    {
      title: "营业状态",
      dataIndex: "enabled",
      key: "enabled",
      render: (record) => <Tag>{record ? "营业中" : "停业中"}</Tag>,
    },
    {
      title: "门店名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "主营业态",
      dataIndex: "businessType",
      key: "businessType",
      render: (record) => {
        if (record === "DINNER") {
          return "正餐";
        } else if (record === "FAST_FOOD") {
          return "快餐";
        } else if (record === "HOT_POT") {
          return "火锅";
        } else if (record === "BARBECUE") {
          return "烧烤";
        } else if (record === "WESTERN_FOOD") {
          return "西餐";
        }
      },
    },
    {
      title: "管理类型",
      dataIndex: "managementType",
      key: "managementType",
      render: (record) => (record === "DIRECT_SALES" ? "直营" : "加盟"),
    },
    {
      title: "营业时间",
      dataIndex: "openingHours",
      key: "openingHours",
      render: (record) => record.openTime + "-" + record.closeTime,
    },
    {
      title: "营业面积",
      dataIndex: "businessArea",
      key: "businessArea",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (_, record) => {
        return (
          <p style={{ color: "orange" }}>
            <span
              onClick={() => {
                console.log(record);
                navigate(`/edit/${record.businessNo}`);
              }}
              style={{ cursor: "pointer" }}
            >
              编辑
            </span>
            |
            <Popconfirm
              title={
                record.enabled ? (
                  <span>
                    确认停用?
                    <br />
                    停用后门店将移至停用门店第一位
                  </span>
                ) : (
                  <span>
                    确认启用?
                    <br />
                    启用后门店将移至最上方
                  </span>
                )
              }
              onConfirm={() => {
                switchShop(record.enabled, record.businessNo, record.version);
              }}
              okText="确定"
              cancelText="取消"
            >
              <span style={{ cursor: "pointer" }}>
                {record.enabled ? "停用" : "启用"}
              </span>
            </Popconfirm>
          </p>
        );
      },
    },
  ];

  const onFinish = (values) => {
    console.log(values);
    searchForPage(index, pageSize, values);
  };

  return (
    <>
      <Row style={{ backgroundColor: "rgb(230,230,230)" }}>
        <Col offset={10}>
          <span>门店管理</span>
        </Col>
        <Col offset={8}>
          <Button
            style={{
              backgroundColor: "orange",
              borderRadius: "5px",
            }}
            onClick={() => {
              navigate("/create");
            }}
          >
            创建新门店
          </Button>
        </Col>
      </Row>

      {/* 搜索条件表单 */}
      <Form
        style={{ marginTop: "15px" }}
        name="search"
        onFinish={onFinish}
        form={searchForm}
      >
        <Row>
          <Col span={6}>
            <Form.Item label="营业状态" name="enabled">
              <Select defaultValue={null}>
                <Option value={null}>所有</Option>
                <Option value={true}>营业中</Option>
                <Option value={false}>停业中</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col offset={2} span={6}>
            <Form.Item label="主营业态" name="businessType">
              <Select defaultValue={null}>
                <Option value={null}>所有</Option>
                <Option value="DINNER">正餐</Option>
                <Option value="FAST_FOOD">快餐</Option>
                <Option value="HOT_POT">火锅</Option>
                <Option value="BARBECUE">烧烤</Option>
                <Option value="WESTERN_FOOD">西餐</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col offset={2} span={6}>
            <Form.Item label="管理类型" name="managementType">
              <Select defaultValue={null}>
                <Option value={null}>所有</Option>
                <Option value="DIRECT_SALES">直营</Option>
                <Option value="ALLIANCE">加盟</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={6}>
            <Form.Item label="门店名" name="keyword">
              <Input />
            </Form.Item>
          </Col>
          <Col offset={1}>
            <Form.Item>
              <Button
                htmlType="submit"
                style={{
                  width: "100px",
                  backgroundColor: "orange",
                  borderRadius: "5px",
                }}
              >
                搜索
              </Button>
            </Form.Item>
          </Col>
          <Col offset={1}>
            <Form.Item>
              <Button
                htmlType="reset"
                style={{
                  width: "100px",
                  backgroundColor: "rgb(230,230,230)",
                  borderRadius: "5px",
                }}
              >
                重置
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>

      {/* 门店展示表格 */}
      <Table
        columns={shopColumns}
        dataSource={dataSource}
        pagination={false}
        rowKey={(record) => record.id}
      ></Table>

      {/* 分页按钮组件 */}
      {pageArray.map((page) => {
        return (
          <Button
            style={{ marginLeft: "10px" }}
            onClick={() => {
              setIndex(page);
            }}
          >
            {page}
          </Button>
        );
      })}

      <span style={{ marginLeft: "10px" }}>
        共{totalPageCount}页，当前第{index}页
      </span>

      {/* 修改页码尺寸控件 */}
      <Select
        defaultValue={10}
        onChange={(value) => {
          setIndex(1);
          setPageSize(value);
        }}
        style={{ width: 40, marginLeft: 10 }}
      >
        {[1, 2, 4, 6, 8, 10, 20, 30, 40, 50].map((value) => {
          return <Option value={value}>{value}</Option>;
        })}
      </Select>
      <span style={{ marginLeft: "10px" }}>项一页</span>
    </>
  );
}

export default Shop;
